﻿using StartEAS_API.Utils;
using StartsEAS_API.DAL.DALTools;
using StartsEAS_API.Model;
using StartsEAS_API.Model.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace StartsEAS_API.DAL.ResultsD
{
    public class ResultsDAL
    {
        private readonly StarsEASContext _context;

        public ResultsDAL(StarsEASContext context)
        {
            _context = context;
        }
        /// <summary>
        /// 查询所有成绩信息
        /// </summary>
        /// <returns></returns>
        public ResultUtils GetAllResults()
        {
            StarsEASContext _context = new StarsEASContext();
            var results = (from result in _context.Results
                           join course in _context.Courses on result.CourseId equals course.CourseId
                           join worker in _context.Workers on result.WorkerId equals worker.WorkerId
                           join Student in _context.Students on result.StuId equals Student.StuId
                           select new
                           {
                               ResultId = result.Id,
                               StuId = Student.StuId,
                               StuName = Student.StuName,
                               CourseId = course.CourseId,
                               CourseName = course.CourseName,
                               WorkerId = worker.WorkerId,
                               WorkerName = worker.WorkerName,
                               ClassId = result.ClassId,
                               Score = result.Score,
                               OpeningDate = result.OpeningDate,
                               ResultStatus = result.ResultsStatus,
                               ResultNote = result.ResultsNote
                           }).ToList();
            AppLog.WriteInfo($"查询成绩信息---查询到{results.Count()}条成绩信息", true);
            return new ResultUtils() { code = 200, message = results };
        }
        /// <summary>
        /// 根据Token查询成绩表
        /// </summary>
        /// <param name="token">学生或老师token</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public IEnumerable<Object> GetResultsByToken(string token)
        {
            StarsEASContext _context = new StarsEASContext();
            User user = _context.Users.Where(u => u.Token.Equals(token)).FirstOrDefault();
            if (user == null)
            {
                AppLog.WriteError($"查询成绩信息---用户{token}尝试登录但是登录失败", true);
                throw new ArgumentException("Token有误");
            }
            //判断是否为学生
            if (token.IsStudent(_context))
            {
                Model.Models.Student student = token.GetStudentByToken(_context);
                //IEnumerable<Result> results = _context.Results.Where(r => r.StuId == student.StuId).ToList();
                var results = (from result in _context.Results
                               join course in _context.Courses on result.CourseId equals course.CourseId
                               join worker in _context.Workers on result.WorkerId equals worker.WorkerId
                               join Student in _context.Students on result.StuId equals Student.StuId
                               where result.StuId == student.StuId
                               select new
                               {
                                   ResultId = result.Id,
                                   StuId = Student.StuId,
                                   StuName = Student.StuName,
                                   CourseId = course.CourseId,
                                   CourseName = course.CourseName,
                                   WorkerId = worker.WorkerId,
                                   WorkerName = worker.WorkerName,
                                   ClassId = result.ClassId,
                                   Score = result.Score,
                                   OpeningDate = result.OpeningDate,
                                   ResultStatus = result.ResultsStatus,
                                   ResultNote = result.ResultsNote
                               }).ToList();
                AppLog.WriteInfo($"查询成绩信息---{student.StuName}学生查询到{results.Count()}条成绩信息", true);
                return results;
            }
            //不是学生，则为老师
            else
            {
                Worker workers = token.GetWorkerByToken(_context);
                var results = (from result in _context.Results
                               join course in _context.Courses on result.CourseId equals course.CourseId
                               join worker in _context.Workers on result.WorkerId equals worker.WorkerId
                               join Student in _context.Students on result.StuId equals Student.StuId
                               where result.WorkerId == workers.WorkerId
                               select new
                               {
                                   ResultId = result.Id,
                                   StuId = Student.StuId,
                                   StuName = Student.StuName,
                                   CourseId = course.CourseId,
                                   CourseName = course.CourseName,
                                   WorkerId = worker.WorkerId,
                                   WorkerName = worker.WorkerName,
                                   ClassId = result.ClassId,
                                   Score = result.Score,
                                   OpeningDate = result.OpeningDate,
                                   ResultStatus = result.ResultsStatus,
                                   ResultNote = result.ResultsNote
                               }).ToList();
                AppLog.WriteInfo($"查询成绩信息---{workers.WorkerName}老师查询到{results.Count()}条成绩信息", true);
                return results;
            }
        }
        /// <summary>
        /// 根据班级查询成绩表
        /// </summary>
        /// <param name="token">教务处Token</param>
        /// <param name="classId">班级编号</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException"></exception>
        public IEnumerable<Object> GetResultsByClassId(string token, string classId){
            StarsEASContext _context = new StarsEASContext();
            User user = _context.Users.Where(u => u.Token.Equals(token)).FirstOrDefault();
            if (user == null)
            {
                AppLog.WriteError($"查询成绩信息---{token}尝试登录但登录失败", true);
                throw new ArgumentException("Token有误");
            }
            if (user.PositionId != 6)
            {
                AppLog.WriteError($"查询成绩信息---{token}尝试使用非教务处账户登录", true);
                throw new ArgumentException("权限不足");
            }
            var results = (from result in _context.Results
                           join course in _context.Courses on result.CourseId equals course.CourseId
                           join worker in _context.Workers on result.WorkerId equals worker.WorkerId
                           join Student in _context.Students on result.StuId equals Student.StuId
                           where result.ClassId == classId
                           select new
                           {
                               ResultId = result.Id,
                               StuId = Student.StuId,
                               StuName = Student.StuName,
                               CourseId = course.CourseId,
                               CourseName = course.CourseName,
                               WorkerId = worker.WorkerId,
                               WorkerName = worker.WorkerName,
                               ClassId = result.ClassId,
                               Score = result.Score,
                               OpeningDate = result.OpeningDate,
                               ResultStatus = result.ResultsStatus,
                               ResultNote = result.ResultsNote
                           }).ToList();
            AppLog.WriteInfo($"查询成绩信息---查询到{results.Count()}条成绩信息", true);
            return results;
        }
        /// <summary>
        /// 新增一条成绩信息
        /// </summary>
        /// <param name="result">成绩信息</param>
        /// <returns>受影响行数</returns>
        public int AddResults(Result result) {
            StarsEASContext _context = new StarsEASContext();
            result.Id = 0;
            _context.Results.Add(result);
            return _context.SaveChanges();
        }
        /// <summary>
        /// 修改成绩信息
        /// </summary>
        /// <param name="data">新成绩信息</param>
        /// <returns>受影响行数</returns>
        public int UpdateResults(Result data) {
            StarsEASContext _context = new StarsEASContext();
            if (data == null) {
                AppLog.WriteError($"修改成绩信息---成绩信息为空", true);
                return -1;
            }
            Result result = _context.Results.Find(data.Id);
            if (result == null) {
                AppLog.WriteError($"修改成绩信息---{data.Id}未查询到成绩信息", true);
                return -1;
            }
            result.StuId = data.StuId;
            result.CourseId = data.CourseId;
            result.WorkerId = data.WorkerId;
            result.ClassId = data.ClassId;
            result.Score = data.Score;
            result.OpeningDate = data.OpeningDate;
            result.ResultsStatus = data.ResultsStatus;
            result.ResultsNote = data.ResultsNote;
            int results = _context.SaveChanges();
            if (results == 0) {
                AppLog.WriteError($"修改成绩信息---{data.Id}修改失败或与原数据相同", true);
                return -1;
            }
            AppLog.WriteInfo($"修改成绩信息---{data.Id}修改成功", true);
            return results;
        }

        public Result GetResultsById(int id) {
            StarsEASContext _context = new StarsEASContext();
            Result result = _context.Results.Find(id);
            if(result == null)
            {
                AppLog.WriteError($"查询成绩信息---{id}未查询到成绩信息", true);
                return null;
            }
            AppLog.WriteInfo($"查询成绩信息---{id}查询到成绩信息", true);
            return result;
        }
    }
}
